import 'dart:async';

import 'package:auto_route/auto_route.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_news/common/api/apis.dart';
import 'package:flutter_news/common/entity/entitys.dart';
import 'package:flutter_news/common/entity/news.dart';
import 'package:flutter_news/common/utils/utils.dart';
import 'package:flutter_news/common/values/cache.dart';
import 'package:flutter_news/common/values/storage.dart';
import 'package:flutter_news/pages/main/categories_widget.dart';
import 'package:flutter_news/pages/main/recommend_widget.dart';
import 'package:skeletonizer/skeletonizer.dart';

import 'channels_widget.dart';
import 'news_item_widget.dart';
import 'newsletter_widget.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> with AutomaticKeepAliveClientMixin{
  NewsPageListResponseEntity? _newsPageList; // 新闻翻页
  NewsItem? _newsRecommend; // 新闻推荐
  List<CategoryResponseEntity> _categories = []; // 分类
  List<ChannelResponseEntity>? _channels; // 频道

  String _selCategoryCode = ""; // 选中的分类Code

  late EasyRefreshController _controller; // EasyRefresh控制器

  var isShowSkele = false; // 是否展示骨架屏

  @override
  void initState() {
    super.initState();
    _controller = EasyRefreshController(controlFinishRefresh: true);
    _loadAllData();
    _loadLatestWithDiskCache();
  }

  @override
  Widget build(BuildContext context) {
    // 如果涉及滚动嵌套，则使用 EasyRefresh.builder，共享一个物理遍历，否则会出现首次下拉，没有看到加载视图
    // 没有滚动嵌套，则使用 EasyRefresh，
    return EasyRefresh.builder(
      controller: _controller,
      header: ClassicHeader(),
      callRefreshOverOffset: 0.01.toDouble(),
      onRefresh: () async {
        setState(() {
          isShowSkele = true;
        });
        await _loadNewsData(
          _selCategoryCode,
          refresh: true,
        );

        _controller.finishRefresh();
      },
      childBuilder: (context, physics) {
        return SingleChildScrollView(
          physics: physics,
          child: Skeletonizer(
            enabled: isShowSkele,
            enableSwitchAnimation: true,
            child: Column(
              children: <Widget>[
                _buildCategories(),
                Divider(height: 1),
                _buildRecommend(),
                Divider(height: 1),
                _buildChannels(),
                Divider(height: 1),
                _buildNewsList(),
                Divider(height: 1),
                _buildEmailSubscribe(),
              ],
            ),
          ),
        );
      },
    );
  }

  // 读取所有数据
  _loadAllData() async {
    _categories = await NewsAPI.categories(
      context: context,
      cacheDisk: true,
    );
    _channels = await NewsAPI.channels(
      context: context,
      cacheDisk: true,
    );
    _newsRecommend = await NewsAPI.newsRecommend(
      context: context,
      cacheDisk: true,
    );
    _newsPageList = await NewsAPI.newsPageList(
      context: context,
      cacheDisk: true,
    );

    _selCategoryCode = _categories.first.code;

    if (mounted) {
      setState(() {
        isShowSkele = false;
      });
    }
  }

  // 如果有磁盘缓存，延迟3秒拉取更新档案
  _loadLatestWithDiskCache() {
    if (CACHE_ENABLE == true) {
      var cacheData = StorageUtil().getJson(STORAGE_INDEX_NEWS_CACHE_KEY);
      if (cacheData != null) {
        Timer(Duration(seconds: 3), () {
          _controller.callRefresh();
        });
      }
    }
  }

  // 拉取推荐、新闻
  _loadNewsData(
    categoryCode, {
    bool refresh = false,
  }) async {
    _selCategoryCode = categoryCode;
    _newsRecommend = await NewsAPI.newsRecommend(
      context: context,
      params: NewsRecommendRequestEntity(
          categoryCode: categoryCode, channelCode: ""),
      refresh: refresh,
      cacheDisk: true,
    );
    _newsPageList = await NewsAPI.newsPageList(
      context: context,
      params: NewsPageListRequestEntity(categoryCode: categoryCode),
      refresh: refresh,
      cacheDisk: true,
    );

    if (mounted) {
      setState(() {
        isShowSkele = false;
      });
    }
  }

  // 分类菜单
  Widget _buildCategories() {
    return newsCategoriesWidget(
      categories: _categories,
      selCategoryCode: _selCategoryCode,
      onTap: (CategoryResponseEntity item) {
        setState(() {
          _selCategoryCode = item.code;
        });
      },
    );
  }

  // 推荐阅读
  Widget _buildRecommend() {
    return _newsRecommend == null // 数据没到位，可以用骨架图展示
        ? Container()
        : recommendWidget(_newsRecommend!, context: context);
  }

  // 频道
  Widget _buildChannels() {
    return _channels == null
        ? Container()
        : newsChannelsWidget(
            channels: _channels!,
            onTap: (ChannelResponseEntity item) {},
          );
  }

  // 新闻列表
  Widget _buildNewsList() {
    return _newsPageList == null
        ? Container(
            height: duSetHeight(161 * 5 + 100.0),
          )
        : Column(
            children: _newsPageList!.items.map((item) {
              return Column(
                children: <Widget>[
                  newsItem(item),
                  Divider(height: 1),
                ],
              );
            }).toList(),
          );
  }

  // ad 广告条
  // 邮件订阅
  Widget _buildEmailSubscribe() {
    return newsletterWidget();
  }

  @override
  bool get wantKeepAlive => true;
}
